<template>
  <view class="container">
    <S1Header title="存单管理" :on-back="onBack">
      <template #right>
        <view class="filter" @click="onFilter">
          <image class="filter-icon" src="https://ceshiweb.picaime.com/static/images/filter.png" />
        </view>
      </template>
    </S1Header>

    <view class="search-bar">
      <view class="search-icon" />
      <input v-model="keyword" class="search-input" placeholder="搜索买家名称或单号" confirm-type="search" @confirm="onSearch">
    </view>

    <!-- 加载中提示 -->
    <u-loadmore v-if="loading" status="loading" />

    <!-- 空数据提示 -->
    <u-empty v-if="!loading && carqudanList.length === 0" mode="data" text="暂无存单数据" />

    <!-- 存单列表 -->
    <view v-if="carqudanList.length > 0" class="carqudan-list">
      <view v-for="(item, index) in carqudanList" :key="item.id || index" class="carqudan-item">
        <view class="item-top">
          <text class="buyer-name">
            {{ item.name }}
          </text>
          <text class="time">
            挂单时间：{{ formatDateTime(item.guadan) }}
          </text>
        </view>

        <view class="item-middle">
          <view class="info-row">
            <text class="label">
              操作员：
            </text>
            <text class="value">
              {{ item.user.name }}
            </text>
          </view>
          <view class="info-row">
            <text class="label">
              单号：
            </text>
            <text class="value">
              {{ item.id }}
            </text>
          </view>
          <view class="info-row">
            <text class="label">
              创建时间：
            </text>
            <text class="value">
              {{ formatDateTime(item.time) }}
            </text>
          </view>
          <view class="info-row">
            <text class="label">
              商品数量：
            </text>
            <text class="value">
              {{ item.car_num }}种
            </text>
          </view>
          <view class="info-row">
            <text class="label">
              总金额：
            </text>
            <text class="value price">
              ¥{{ formatPrice(item.total_price) }}
            </text>
          </view>
        </view>

        <view class="item-bottom">
          <button class="btn-use" @click="onUseCarqudan(item)">
            使用
          </button>
          <button class="btn-detail" @click="viewDetail(item)">
            查看明细
          </button>
          <button class="btn-delete" @click="onDeleteCarqudan(item)">
            删除
          </button>
        </view>
      </view>
    </view>

    <!-- 底部提示 -->
    <view v-if="carqudanList.length > 0" class="footer-tip">
      {{ loadStatus === 'nomore' ? '已加载全部数据' : '' }}
    </view>

    <!-- 加载更多 -->
    <u-loadmore v-if="carqudanList.length > 0 && !loading" :status="loadStatus" @loadmore="loadMore" />
  </view>
</template>

<script setup lang="ts">
import type { CarqudanItem } from '@/api/order/types';
import { computed, onMounted, ref } from 'vue';
import { OrderApi } from '@/api';
import * as S1Header from '@/components/S1Header.vue';

// 页面数据
const keyword = ref('');
const loading = ref(false);
const carqudanList = ref<CarqudanItem[]>([]);

// 加载状态控制
const loadStatus = computed(() => {
  if (loading.value) return 'loading';
  return 'nomore';
});

// 返回上一页
const onBack = () => {
  uni.navigateBack();
};

// 筛选功能
const onFilter = () => {
  uni.showToast({
    title: '筛选功能开发中',
    icon: 'none',
  });
};

// 搜索功能
const onSearch = () => {
  fetchData();
};

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr || dateStr === '0') return '-';
  return dateStr;
};

// 格式化价格
const formatPrice = (price: number) => {
  return price.toFixed(2);
};

// 使用存单
const onUseCarqudan = (item: CarqudanItem) => {
  uni.showModal({
    title: '使用存单',
    content: `确认使用买家"${item.name}"的存单吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '功能开发中',
          icon: 'none',
        });
      }
    },
  });
};

// 查看存单详情
const viewDetail = (item: CarqudanItem) => {
  uni.navigateTo({
    url: `/pages/order/carqudan-detail?id=${item.id}`,
  });
};

// 删除存单
const onDeleteCarqudan = (item: CarqudanItem) => {
  uni.showModal({
    title: '删除存单',
    content: `确认删除买家"${item.name}"的存单吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '功能开发中',
          icon: 'none',
        });
      }
    },
  });
};

// 加载更多数据（暂不实现分页）
const loadMore = () => {
  // 暂不实现
};

// 获取买家存单数据
const fetchData = async () => {
  try {
    loading.value = true;

    const params = keyword.value ? { keywords: keyword.value } : undefined;
    const res = await OrderApi.getMaijiaCarqudan(params);

    if (res.code === 200) {
      carqudanList.value = res.data || [];
    }
    else {
      uni.showToast({
        title: res.msg || '获取存单数据失败',
        icon: 'none',
      });
      carqudanList.value = [];
    }
  }
  catch (error) {
    console.error('获取存单数据失败', error);
    uni.showToast({
      title: '获取存单数据失败',
      icon: 'none',
    });
    carqudanList.value = [];
  }
  finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchData();
});

// 监听页面显示
uni.$on('hook:onShow', () => {
  fetchData();
});
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  min-height: 100vh;
}

.filter {
  position: absolute;
  right: 20rpx;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.filter-icon {
  width: 32rpx;
  height: 32rpx;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.search-icon {
  width: 40rpx;
  height: 40rpx;
  background: url("https://ceshiweb.picaime.com/static/images/search.png") no-repeat center;
  background-size: contain;
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  height: 40rpx;
  font-size: 24rpx;
  border: none;
  outline: none;
}

.carqudan-list {
  display: flex;
  flex-direction: column;
  padding: 10rpx 20rpx;
}

.carqudan-item {
  background-color: #fff;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  padding: 20rpx;
}

.item-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.buyer-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.time {
  font-size: 24rpx;
  color: #999;
}

.item-middle {
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 26rpx;
  color: #666;
  width: 160rpx;
}

.value {
  font-size: 26rpx;
  color: #333;
  flex: 1;
}

.price {
  color: #f54444;
  font-weight: bold;
}

.item-bottom {
  display: flex;
  justify-content: flex-end;
  padding-top: 15rpx;
  gap: 15rpx;
}

.btn-use,
.btn-detail,
.btn-delete {
  font-size: 24rpx;
  padding: 6rpx 20rpx;
  border-radius: 6rpx;
  border: none;
}

.btn-use {
  background-color: #07c160;
  color: white;
}

.btn-detail {
  background-color: #1e90ff;
  color: white;
}

.btn-delete {
  background-color: #ff4444;
  color: white;
}

.footer-tip {
  text-align: center;
  font-size: 24rpx;
  color: #999;
  padding: 20rpx 0;
}
</style>
